#include<iostream>
#include<string>
#include<pthread.h>
#include<unistd.h>

int tickets=1000;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;

void* threadRoutine(void* args)
{
    std::string name=static_cast<const char*>(args);
     while (true)
    {
        
        pthread_mutex_lock(&mutex);//加锁
        if(tickets>0)
        {
            usleep(2000);
            std::cout<<name<<"get a ticket:"<<tickets--<<std::endl;//临界区（访问临界资源的代码段）
            pthread_mutex_unlock(&mutex);//解锁
        }
        else
        {
            pthread_mutex_unlock(&mutex);//解锁
            break;
            

        }
    }
    //模拟抢票后的操作
    usleep(15);

}
int main()
{
    pthread_t tids[4];
    int n=sizeof(tids)/sizeof(tids[0]);
    for(int i=0;i<n;i++)
    {
        char* name=new char[64];
        snprintf(name,64,"thread-%d",i+1);
        pthread_create(tids+i,nullptr,threadRoutine,name);
    }
    for(int i=0;i<n;i++)
    {
        pthread_join(tids[i],nullptr);
    }
    return 0;

}
